package tw.asap.plus.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import jp.wasabeef.recyclerview.animators.FadeInRightAnimator;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.entity.User;
import tw.asap.plus.entity.request.CommonRequestParams;
import tw.asap.plus.entity.response.OrderCreated;
import tw.asap.plus.entity.response.ResponseDataWrapper;
import tw.asap.plus.network.config.HRetrofitCreator;
import tw.asap.plus.network.service.OrderService;
import tw.asap.plus.ui.activity.LoginAsapActivity;
import tw.asap.plus.ui.activity.MainActivity;
import tw.asap.plus.ui.adapter.OrderAdapter;
import tw.asap.plus.ui.custom.AppBar;
import tw.asap.plus.utils.Toaster;

/**
 * Created by Yax on 15/11/9.
 */
public class OrderFragment extends Fragment {

    View view;
    @InjectView(R.id.appbar)
    AppBar appbar;
    @InjectView(R.id.recycler_view)
    RecyclerView recyclerView;
    @InjectView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @InjectView(R.id.extra_layout)
    FrameLayout extraLayout;
    private int pageSize = 10;
    private boolean isLoading;
    private boolean hasMore;
    private boolean isBackground;
    private int currentPage;
    private ArrayList<OrderCreated> orderCreatedArrayList = new ArrayList<>();
    OrderAdapter adapter;


    public static OrderFragment newInstance() {
        return new OrderFragment();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (MainActivity.REFRESH_ORDER_LIST == 1 || MainActivity.REFRESH_ALL_FRAGMENT == 1) {

            if(adapter == null) {
                setUpRecyclerView();
                reload(false);
                MainActivity.REFRESH_ALL_FRAGMENT = 0;
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (swipeRefreshLayout != null)
            swipeRefreshLayout.setRefreshing(false);
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_orders, null);
        } else {
            if (view.getParent() != null)
                ((ViewGroup) view.getParent()).removeView(view);
        }
        ButterKnife.inject(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!User.hasLogin()) {
            initExtraLayout(0);
        } else {
            setUpRecyclerView();
            reload(true);
        }
    }

    private void setUpRecyclerView() {
        swipeRefreshLayout.setColorSchemeResources(R.color.palette_red);
        swipeRefreshLayout.setOnRefreshListener(() -> reload(false));
        adapter = new OrderAdapter(getActivity(), recyclerView, orderCreatedArrayList);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.setItemAnimator(new FadeInRightAnimator());
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (mLayoutManager.findLastVisibleItemPosition() + 1 == orderCreatedArrayList.size() - 1
                        && orderCreatedArrayList.size() > pageSize - 1 && !isLoading && hasMore) {
//                    Log.d("onScrolled", "end");
                }
            }
        });
    }

    private void reload(boolean b) {
        if (swipeRefreshLayout != null && !isBackground)
            swipeRefreshLayout.setRefreshing(true);
        currentPage = 0;

        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<List<OrderCreated>>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<List<OrderCreated>>> subscriber) {
                OrderService service = creator.getService(OrderService.class);
                subscriber.onNext(service.getCreatedOrders(new CommonRequestParams()));
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<List<OrderCreated>>>() {
                    @Override
                    public void onCompleted() {
                        swipeRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        swipeRefreshLayout.setRefreshing(false);
                        if (e.getMessage().equals(ConstValue.INTERNET_ERROR)) {
                            initExtraLayout(2);
                        }
                        Toaster.s(getActivity(), e.getMessage());
                    }

                    @Override
                    public void onNext(ResponseDataWrapper<List<OrderCreated>> orderList) {
                        if (orderList.respcd.equals(ConstValue.RESPCD)) {
                            if (orderList.data.size() == 0) {
                                initExtraLayout(1);
                            } else {
                                swipeRefreshLayout.setVisibility(View.VISIBLE);
                                orderCreatedArrayList.clear();
                                orderCreatedArrayList.addAll(orderList.data);
                                adapter.notifyDataSetChanged();
                                MainActivity.REFRESH_ORDER_LIST = 0;
                            }
                        } else {
                            Toaster.s(getActivity(), orderList.resperr);
                        }
                    }
                });


    }


    public void initExtraLayout(int state) {
        swipeRefreshLayout.setVisibility(View.GONE);
        extraLayout.setVisibility(View.VISIBLE);
        switch (state) {
            case 0://loading
                swipeRefreshLayout.setVisibility(View.GONE);
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_no_collection, extraLayout);
                ((ImageView) view.findViewById(R.id.icon)).setImageResource(R.drawable.icon_record_empty);
                ((TextView) view.findViewById(R.id.empty_hint)).setText(R.string.observe_order_after_login);
                extraLayout.setOnClickListener(v -> {
                    startActivity(new Intent(getActivity(), LoginAsapActivity.class));
                });
                break;
            case 1://noData
                swipeRefreshLayout.setVisibility(View.GONE);
                View emptyView = LayoutInflater.from(getActivity()).inflate(R.layout.layout_no_collection, extraLayout);
                ((ImageView) emptyView.findViewById(R.id.icon)).setImageResource(R.drawable.icon_record_empty);
                ((TextView) emptyView.findViewById(R.id.empty_hint)).setText(getString(R.string.no_order_within_month));
                extraLayout.setOnClickListener(v -> {
                });
                break;
            case 2://noNetwork
                swipeRefreshLayout.setVisibility(View.GONE);
                LayoutInflater.from(getActivity()).inflate(R.layout.layout_nonetwork, extraLayout);
                extraLayout.setOnClickListener(v -> reload(true));
                break;
        }

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (swipeRefreshLayout != null) {
            Log.d("onPause", "swipeRefreshLayout！＝null");
            swipeRefreshLayout.setRefreshing(false);
            swipeRefreshLayout.destroyDrawingCache();
            swipeRefreshLayout.clearAnimation();
        }
    }

}
